﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Giraffe.Core.Common.Messengers;

namespace Giraffe.Core.Model
{
    public class Conversation : IConversation
    {
        private readonly IMessengerConversation _messengerConversation;
        protected List<IMessage> _messages = new List<IMessage>();
        private IMessenger _messenger;

        internal Conversation(IMessenger messenger, IContact contact)
        {
            _messengerConversation = messenger.StartConversation(contact.GetMessaengerContact(messenger.MessengerType));
            _messengerConversation.MessageReceived += OnMessageReceived;
            Companion = contact;
            _messenger = messenger;
        }

        public IContact Companion { get; protected set; }

        public IEnumerable<IMessage> Messages 
        { 
            get
            {
                return _messages;
            }
        }

        public event Action MessagesUpdated;

        public DateTime SendMessage(string text)
        {
            DateTime time = _messengerConversation.SendMessage(text);
            var message = new Message(text, time, _messenger.OwnContact, Companion.GetMessaengerContact(_messenger.MessengerType));
            _messages.Add(message);
            RiseMessagesUpdated();
            return time;
        }

        public IMessenger CurrentMessenger
        {
            get
            {
                return _messenger;
            }
        }

        public void Close()
        {
            _messengerConversation.Close();
        }

        protected void RiseMessagesUpdated()
        {
            Action action = MessagesUpdated;
            if (action != null)
            {
                action();
            }
        }
        
        private void OnMessageReceived(IMessage message)
        {
            _messages.Add(message);
            RiseMessagesUpdated();
        }
    }
}
